//
//  FYPieView.m
//  FYChartDemo
//
//  Created by Felix Yin on 2017/6/1.
//  Copyright © 2017年 Felix Yin. All rights reserved.
//

#import "FYPieView.h"
#import <Charts/Charts-Swift.h>

#define CenterX  [UIScreen mainScreen].bounds.size.width * 0.5
#define CenterY [UIScreen mainScreen].bounds.size.height * 0.5

@interface FYPieView ()<ChartViewDelegate>

@property (nonatomic, strong) PieChartView *pieChartView;
@property (nonatomic, strong) NSArray *titleArray;

@end

@implementation FYPieView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    [self addSubview:self.pieChartView];
    return self;
}


- (void)updatePieViewData:(NSArray *)titleArray{
    self.titleArray = titleArray;
    [self pieChartData];
    if (titleArray.count < 2) {
        _pieChartView.rotationEnabled = NO;
    }else{
        [self spinToNinetyAngle];
    }
}

//设置数据
- (void) pieChartData{
    NSMutableArray *values = [[NSMutableArray alloc] init];
    //区块数据
    for (int i = 0; i < self.titleArray.count; i++) {
        double value = 10 + 5 * (i + 1 );
        if(value > 0){
            NSString *title = [self.titleArray objectAtIndex:i];
            PieChartDataEntry *dataEntry = [[PieChartDataEntry alloc] initWithValue:value  label:title];
            [values addObject:dataEntry];
        }
    }
    
    //data set
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:values label:@""];
    
    //add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    dataSet.colors = colors;
    
    dataSet.drawValuesEnabled = NO; //是否绘制显示数据
    dataSet.sliceSpace = 0.0; //相邻区块之间的间距
    //    dataSet.iconsOffset = CGPointMake(0, 40);
    dataSet.selectionShift = 0;//选中区块时, 放大的半径
    dataSet.xValuePosition = PieChartValuePositionInsideSlice;//名称位置
    dataSet.yValuePosition = PieChartValuePositionOutsideSlice;//数据位置
    
    //数据与区块之间的用于指示的折线样式
    dataSet.valueLinePart1OffsetPercentage = 0.85;//折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
    dataSet.valueLinePart1Length = 0.5;//折线中第一段长度占比
    dataSet.valueLinePart2Length = 0.4;//折线中第二段长度最大占比
    dataSet.valueLineWidth = 1;//折线的粗细
    dataSet.valueLineColor = [UIColor brownColor];//折线颜色
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    //设置显示数据格式
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1; //小数位数
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @"%";
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    self.pieChartView.data = data;
}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([self.delegate respondsToSelector:@selector(fyPieView:selectedIndex:)]) {
        NSLog(@"end ====");
        NSInteger ind = [self spinToNinetyAngle];
        [self.delegate fyPieView:self selectedIndex:ind];
    }
}


/**
 *  旋转到重心位置
 */
- (NSInteger) spinToNinetyAngle{
    if(_titleArray.count < 2){
        return 0;
    }
    
    NSArray *angles = _pieChartView.absoluteAngles;
    NSInteger ind = [_pieChartView indexForAngle:90]; //找当前 data
    double angle = [[angles objectAtIndex:ind] doubleValue];
    double angle2 = [[_pieChartView.drawAngles objectAtIndex:ind] doubleValue];
    // 计算悬停 下来 旋转的角度
    double rotationangle = _pieChartView.rotationAngle;
    double rawangle = _pieChartView.rawRotationAngle;
    double toAngle = angle - angle2 * 0.5;
    NSString *title = [self.titleArray objectAtIndex:ind];
    NSLog(@"title === > %@",title);
    if (toAngle <= 90) {
        rawangle > 0 ? [_pieChartView spinWithDuration:0.5 fromAngle:_pieChartView.rotationAngle toAngle:90 - toAngle] : [_pieChartView spinWithDuration:0.5 fromAngle:fabs(rawangle) toAngle:90 - toAngle];
        NSLog(@"rawangle === %@  rotationangle === %@",@(rawangle),@(rotationangle));
    }else{
        [_pieChartView spinWithDuration:0.5 fromAngle:rotationangle toAngle:360 - (toAngle - 90)];
        NSLog(@"rawangle 😝 === %@  rotationangle === %@",@(rawangle),@(rotationangle));
    }
    return ind;
}




#pragma mark PieChartDelegate Override

- (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView entry:(ChartDataEntry * _Nonnull)entry highlight:(ChartHighlight * _Nonnull)highlight{
    if ([self.delegate respondsToSelector:@selector(fyPieView:selectedIndex:)]) {
        NSLog(@"chartValueSelected😁😁😁😁");
        NSInteger ind = [self spinToNinetyAngle];
        [self.delegate fyPieView:self selectedIndex:ind];
    }
}


- (void)chartValueNothingSelected:(ChartViewBase * _Nonnull)chartView{
    NSLog(@"chartValueNothingSelected    ======== %@",chartView);
}


- (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{
    NSLog(@"chartScaled ======= %@      ======= %@ ====== %@",chartView,@(scaleX),@(scaleY));
}


- (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY{
    NSLog(@"chartTranslated ======== %@   ====== %@   ====== %@",chartView,@(dX),@(dY));
}


#pragma mark Lazy Loading

- (PieChartView *) pieChartView{
    if (!_pieChartView) {
        _pieChartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width,  self.frame.size.height)];
        _pieChartView.center = self.center;
        _pieChartView.delegate = self;
        _pieChartView.backgroundColor = [UIColor lightGrayColor];
        //饼图样式设置
        [_pieChartView setExtraOffsetsWithLeft:0 top:0 right:0 bottom:0]; //饼图距离边缘距离
        _pieChartView.usePercentValuesEnabled = YES; //是否根据所提供的数据, 将显示数据转换为百分比格式
        _pieChartView.dragDecelerationEnabled = YES;  //拖拽饼状图后是否有惯性效果
        _pieChartView.drawSliceTextEnabled = YES; //是否显示区块文本
        
        //设置饼状图中心文本
        if(_pieChartView.isDrawHoleEnabled){
            _pieChartView.drawCenterTextEnabled = YES;
            NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:@"饼图测试"];
            [centerText setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
                                        NSForegroundColorAttributeName: [UIColor orangeColor]} range:NSMakeRange(0, centerText.length)];
            _pieChartView.centerAttributedText = centerText;
        }
        
        //设置饼状图描述
        _pieChartView.chartDescription.enabled = NO; //是否显示 chart view 描述
        if(_pieChartView.chartDescription.enabled){
            _pieChartView.descriptionText = @"饼图";
            _pieChartView.descriptionFont = [UIFont systemFontOfSize:10];
            _pieChartView.descriptionTextColor = [UIColor blueColor];
            _pieChartView.descriptionTextAlign = NSTextAlignmentCenter;
        }
        
        //设置 饼状图 图样样式
        _pieChartView.legend.enabled = NO;
        if (!_pieChartView.legend.enabled) {
            _pieChartView.legend.form = ChartLegendFormNone; //图示样式: 方形、线条、圆形，无
            _pieChartView.legend.maxSizePercent = 1; //图例在饼状图中的大小占比, 这会影响图例的宽高
            _pieChartView.legend.formToTextSpace = 5; //文本间隔
            _pieChartView.legend.font = [UIFont systemFontOfSize:10]; //字体大小
            _pieChartView.legend.textColor = [UIColor grayColor]; //字体颜色
            _pieChartView.legend.position = ChartLegendPositionBelowChartCenter; //图例在饼状图中的位置
            _pieChartView.legend.formSize = 12;//图示大小
        }
    }
    //    [_pieChartView animateWithXAxisDuration:3 easingOption:ChartEasingOptionEaseOutBack];
    return _pieChartView;
}

@end
